package main

import (
	"strings"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func authMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        authHeader := c.GetHeader("Authorization")
        if !strings.HasPrefix(authHeader, "Bearer ") {
            c.JSON(401, gin.H{"error": "Missing or invalid token"})
            c.Abort()
            return
        }

        tokenString := strings.TrimPrefix(authHeader, "Bearer ")
        // 解析 JWT，提取 user_id
        claims := &jwt.StandardClaims{}
        token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
            return []byte("your-super-secret-jwt-key"), nil
        })

        if err != nil || !token.Valid {
            c.JSON(401, gin.H{"error": "Invalid token"})
            c.Abort()
            return
        }

        // 假设 user_id 在 Subject 或自定义字段中
        uid, err := uuid.Parse(claims.Subject)
        if err != nil {
            c.JSON(400, gin.H{"error": "Invalid user ID in token"})
            c.Abort()
            return
        }

        c.Set("user_id", uid)
        c.Next()
    }
}